import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Menu, Icon, Spin, Dropdown, Avatar, Divider, message } from 'antd';
import Debounce from 'lodash-decorators/debounce';
import Link from 'umi/link';

import styles from './index.less';
import auth from 'utils/auth';

class GlobalHeader extends PureComponent {
  componentWillUnmount() {
    this.triggerResizeEvent.cancel();
  }

  componentWillMount() {
    // const { dispatch, loginedUser } = this.props;
    // if (!loginedUser) {
    //   dispatch({
    //     type: 'users/fetchSelfProfile',
    //   }).then(response => {
    //     if (response.code) {
    //       message.warn(
    //         '服务异常，请重新登陆',
    //         () => {
    //           dispatch(routerRedux.push('/login'));
    //         },
    //         2
    //       );
    //     }
    //   });
    // }
  }

  toggle = () => {
    const { collapsed, onCollapse } = this.props;

    onCollapse(!collapsed);
    this.triggerResizeEvent();
  };

  /* eslint-disable */
  @Debounce(600)
  triggerResizeEvent() {
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
  }
  handleMenuClick = e => {
    if (e.key === 'logout') {
      auth.logout();
      this.props.dispatch(routerRedux.push('/login'));
    }
  };

  render() {
    const { loginedUser, collapsed, isMobile, logo } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.handleMenuClick}>
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出登录
        </Menu.Item>
      </Menu>
    );
    console.log('user: ', loginedUser);
    return (
      <div className={styles.header}>
        {isMobile && [
          <Link to="/" className={styles.logo} key="logo">
            <img src={logo} alt="logo" width="32" />
          </Link>,
          <Divider type="vertical" key="line" />,
        ]}
        <Icon
          className={styles.trigger}
          type={collapsed ? 'menu-unfold' : 'menu-fold'}
          onClick={this.toggle}
        />
        <div className={styles.right}>
          {loginedUser ? (
            <Dropdown overlay={menu}>
              <span className={`${styles.action} ${styles.account}`}>
                <Avatar size="small" className={styles.avatar} src={loginedUser.avatar} />
                <span className={styles.name}>{loginedUser.name}</span>
              </span>
            </Dropdown>
          ) : (
            <Spin size="small" style={{ marginLeft: 8 }} />
          )}
        </div>
      </div>
    );
  }
}

if (process.env.UMI_ENV !== 'prod') {
  GlobalHeader.propTypes = {
    dispatch: PropTypes.func.isRequired,
    onCollapse: PropTypes.func.isRequired,
    onCollapse: PropTypes.func.isRequired,
    collapsed: PropTypes.bool.isRequired,
    loginedUser: PropTypes.object,
  };
}

GlobalHeader.defaultProps = {
  dispatch: () => {},
  onCollapse: () => {},
  collapsed: false,
  loginedUser: null,
};

function mapStateToProps({ users }, ownProps) {
  const { onCollapse, collapsed } = ownProps;
  const loginedUser = users ? users.loginedUser : null;
  return {
    onCollapse,
    collapsed,
    loginedUser,
  };
}

export default connect(mapStateToProps)(GlobalHeader);
